package bamin.com.bamindaijia.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.Arith;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.widget.AnimCheckBox;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.blankj.utilcode.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.adapter.InvoiceOrdersAdapter;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.Invoice;
import bamin.com.bamindaijia.model.Order;
import cz.msebera.android.httpclient.Header;

import static com.aiton.administrator.shane_library.shane.utils.Arith.add;

public class InvoiceActivity extends ZjbBaseActivity implements View.OnClickListener {

    private ListView mRecycler_invoice;
    private TextView mTv_invoice_all_price;
    private boolean isCheckAll;
    private LinearLayout mLine_allcheck;
    private AnimCheckBox mAnimCheckBox;
    private TextView mTv_invoice_num;
    private Button mBtn_next;
    private HashMap<Integer, Order> isChecks = new HashMap<>();
    private InvoiceOrdersAdapter mOrdersAdapter;
    private int mUserID;
    private int orderPageCount = 1;
    private List<Order> mDatas = new ArrayList<>();
    private int mPageSize = 1;
    private Double allPrice = 0.00;
    private TextView mTv_no_invoice;
    private BroadcastReceiver recevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action,Constant.BROADCASTCODE.INVOICE)){
                loadOrder();
                mAnimCheckBox.setChecked(false);
                mTv_invoice_num.setText("0");
                mTv_invoice_all_price.setText("0.0");
                allPrice = 0.0;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invoice);
        showLoadingDialog();
        init();
    }

    @Override
    protected void initData() {
        loadOrder();
    }

    /**
     * 加载没有还没开票的订单
     */
    private void loadOrder() {
        mDatas.clear();
        isChecks.clear();
        String url = Constant.Url.LOAD_ORDER_NO_RECEIPT;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("customerId", "" + mUserID);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Log.e("AllOrderActivity", "所有的订单: --->>" + s);
                    cancelLoadingDialog();

                    Invoice invoice = GsonUtils.parseJSON(s, Invoice.class);
                    if (invoice.getStatus() == 0) {
                        if (null != invoice.getDatas()) {
                            List<Order> datas = invoice.getDatas();
                            mDatas.addAll(datas);

                            mTv_no_invoice.setVisibility(View.GONE);
                            mRecycler_invoice.setVisibility(View.VISIBLE);

                            mOrdersAdapter.notifyDataSetChanged();
                        } else {
                            mTv_no_invoice.setVisibility(View.VISIBLE);
                            mRecycler_invoice.setVisibility(View.GONE);
                            Toast.makeText(InvoiceActivity.this, "没有订单", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        Toast.makeText(InvoiceActivity.this, invoice.getMes(), Toast.LENGTH_SHORT).show();
                    }


                } catch (Exception e) {
                    cancelLoadingDialog();
                    Log.e("AllOrderActivity", "下载订单异常");
                    ToastUtils.showShortToast(InvoiceActivity.this,"数据解析异常");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("AllOrderActivity", "下载订单失败");
                ToastUtils.showShortToast(InvoiceActivity.this, "数据下载失败");
                cancelLoadingDialog();
                showSingleDialog();

            }
        });
    }
    public static Intent newIntent(Context context,int userID){
        Intent intent = new Intent(context, InvoiceActivity.class);
        intent.putExtra(Constant.INTENT_KEY.USER_ID, userID);
        return intent;
    }
    private void showSingleDialog() {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, "网络请求失败", "确定");
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                finishTo();
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }

    @Override
    protected void initViews() {
        mAnimCheckBox.setChecked(false);
        mOrdersAdapter = new InvoiceOrdersAdapter(this, mDatas, isChecks);
        mRecycler_invoice.setAdapter(mOrdersAdapter);
    }

    @Override
    protected void setListeners() {
        mBtn_next.setOnClickListener(this);
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.tv_invoice_history).setOnClickListener(this);
        mLine_allcheck.setOnClickListener(this);
        mAnimCheckBox.setOnCheckedChangeListener(getListener());
        mRecycler_invoice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AnimCheckBox mCheck_order = (AnimCheckBox) view.findViewById(R.id.animCheckBox_order);

                if (!mCheck_order.isChecked()) {
                    isChecks.put(position, mDatas.get(position));
                    mCheck_order.setChecked(true);
                    //总价格判断
                    Double finalPriceStr = mDatas.get(position).getFinalPrice();

                    if (finalPriceStr == null) {
                        finalPriceStr = 0.00;

                    }

                    double finalPrice2 = Arith.get2Double(finalPriceStr);

                    allPrice = Arith.add(allPrice, finalPrice2);


                } else {
                    isChecks.remove(position);
                    mCheck_order.setChecked(false);
                    //总价格判断
                    Double finalPriceStr = mDatas.get(position).getFinalPrice();
                    if (finalPriceStr == null) {
                        finalPriceStr = 0.00;
                    }
                    double finalPrice2 = Arith.get2Double(finalPriceStr);
                    allPrice = Arith.sub(allPrice, finalPrice2);
                }
                mAnimCheckBox.setOnCheckedChangeListener(null);//防止子控件的选择变成全选
                if (mDatas.size() == isChecks.size()) {//如果全部选择后，全选选中
                    mAnimCheckBox.setChecked(true);
                } else {
                    mAnimCheckBox.setChecked(false);
                }
                //判断容器不为空，则可以点击
                Log.e("InvoiceActivity", "onItemClick: --->>" + isChecks.size());

                if (isChecks.size() > 0) {

                    mBtn_next.setEnabled(true);
                } else {
                    mBtn_next.setEnabled(false);
                }
                mAnimCheckBox.setOnCheckedChangeListener(getListener());
                mTv_invoice_num.setText("" + isChecks.size());
                mTv_invoice_all_price.setText(allPrice + "");

                mOrdersAdapter.notifyDataSetChanged();
            }
        });

    }


    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mUserID = intent.getIntExtra(Constant.INTENT_KEY.USER_ID, -1);
    }

    @Override
    protected void findID() {
        mRecycler_invoice = (ListView) findViewById(R.id.list_invoice);
        mLine_allcheck = (LinearLayout) findViewById(R.id.line_allcheck);
        mAnimCheckBox = (AnimCheckBox) findViewById(R.id.animCheckBox_all);
        mTv_invoice_num = (TextView) findViewById(R.id.tv_invoice_num);
        mTv_invoice_all_price = (TextView) findViewById(R.id.tv_invoice_all_price);
        mTv_no_invoice = (TextView) findViewById(R.id.tv_no_invoice);
        mBtn_next = (Button) findViewById(R.id.btn_next);



    }


    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter intent = new IntentFilter();
        intent.addAction(Constant.BROADCASTCODE.INVOICE);
        registerReceiver(recevier, intent);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();

        switch (v.getId()) {
            case R.id.line_allcheck:
                if (!mAnimCheckBox.isChecked()) {
                    mAnimCheckBox.setChecked(true);
                } else {
                    mAnimCheckBox.setChecked(false);
                }
                mOrdersAdapter.notifyDataSetChanged();
                break;
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.btn_next:
                intent.setClass(this, InvoiceAddressActivity.class);
                intent.putExtra(Constant.INTENT_KEY.INVOICE, isChecks);
//                intent.putExtra(Constant.INTENT_KEY.USER_ID, mUserID);
                intent.putExtra(Constant.INTENT_KEY.INVOICE_MONEY, allPrice);

                startActivityForResultTo(intent,Constant.REQUEST_RESULT_CODE.INVOICE);
                break;
            case R.id.tv_invoice_history:
                intent.setClass(this, InvoiceHistoryActivity.class);
                intent.putExtra(Constant.INTENT_KEY.USER_ID, mUserID);
                startActivityTo(intent);
                break;
        }
    }


    @NonNull
    private AnimCheckBox.OnCheckedChangeListener getListener() {
        return new AnimCheckBox.OnCheckedChangeListener() {
            @Override
            public void onChange(boolean checked) {
                isCheckAll = checked;
                allPrice = 0.00;
                if (isCheckAll) {
                    for (int i = 0; i < mDatas.size(); i++) {
                        //总价格判断
//
                        Double finalPrice = mDatas.get(i).getFinalPrice();
                        if (finalPrice == null) {
                            finalPrice = 0.00;

                        }
                        double finalPrice2 = Arith.get2Double(finalPrice);
                        allPrice = add(allPrice, finalPrice2);
                        isChecks.put(i, mDatas.get(i));
                    }
                } else {
                    isChecks.clear();
                }
                //判断容器不为空，则可以点击
                if (isChecks.size() > 0) {
                    mBtn_next.setEnabled(true);
                } else {
                    mBtn_next.setEnabled(false);
                }
                mTv_invoice_num.setText("" + isChecks.size());
                mTv_invoice_all_price.setText(allPrice + "");
                mOrdersAdapter.notifyDataSetChanged();
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(recevier);
    }
}
